/**
 * hujun -用户管理 2017-12-22
 */
define([
    // './custom/widgets/js/yufpOrgTree.js',
    // './custom/widgets/js/yufpRoleSelector.js',
    './libs/jsencrypt/jsencrypt.min.js',
    // './custom/widgets/js/yufpDptTree.js',
    './custom/widgets/js/yufpExtTree.js',
    // './custom/plugins/YufpMgrSelector.js'
], function(require, exports) {
    // page加载完成后调用ready方法
    exports.ready = function(hashCode, data, cite) {
        // 注册该功能要用到的数据字典
        yufp.lookup.reg('CUST_GROUP_STATE,MODEL_TYPE');
        var orgId = '';
        var roleLevel = '';
        var roleCode = '';
        for (var i = 0; i < yufp.session.roles.length; i++) {
            if (yufp.session.roles[i].checked != null) {
                roleLevel = yufp.session.roles[i].roleLevel;
                roleCode = yufp.session.roles[i].code;
            }
        }
        // 创建virtual model
        yufp.custom.vue({
            el: '#customerGroup',
            // 以m_开头的属性为UI数据不作为业务数据，否则为业务数据
            data: function() {
                var me = this;
                return {
                    formdata: {}, // 搜索表单绑定
                    groupDataUrl: '/api/marketCustGroup/getGroupList',
                    groupDataParams: {
                        condition: JSON.stringify({
                            userId: yufp.session.userCode,
                            orgId: yufp.session.org.id,
                            roleCode: roleCode,
                            custGroupName: ''
                        })
                    },
                    custGroupEditButton: !yufp.session.checkCtrl('editCustGroup'), // 修改按钮控制
                    custGroupDeleteButton: !yufp.session.checkCtrl('deleteCustGroup'), // 删除按钮控制
                    custGroupSendMessageButton: !yufp.session.checkCtrl('custGroupSendMessage'), // 发送短信按钮控制
                    height: yufp.custom.viewSize().height - 220,
      //               tableColumns: [{
      //                   label: '序号',
      //                   width: '60',
      //                   type: 'index',
      //                   resizable: true,
      //                   sortable: true
      //               },
      //                   {
      //                       label: '主键',
      //                       prop: 'id',
      //                       hidden: true
      //                   },
      //                   {
      //                       label: '客群编号',
      //                       prop: 'custGroupNo'
      //                   },
      //                   {
      //                       label: '客群名称',
      //                       prop: 'custGroupName'
      //                   },
      //                   // {
      //                   //     label: '网格名称',
      //                   //     prop: 'gridName'
      //                   // },
      //                   // {
      //                   // 	label: '客群类型',
      //                   // 	prop: 'custGroupType'
      //                   // },
      //                   {
      //                       label: '客群状态',
      //                       prop: 'custGroupStatus',
      //                       dataCode: 'CUST_GROUP_STATE'
      //                   },
      //                   {
      //                       label: '客户数量',
      //                       prop: 'custGroupNum'
      //                   },
      //                   {
      //                       label: '创建时间',
      //                       prop: 'createTime'
      //                   },
      //                   {
      //                       label: '创建人',
      //                       prop: 'createUserName'
      //                   },
						
      //               ],
                    // 表单是否显示
                    dialogFormVisible: false,
                    // 表单是否可用
                    formDisabled: false,
                    // 表单操作状态
                    viewType: 'DETAIL',

                    updateFields: [{
                        columnCount: 2,
                        fields: [{
                            field: 'id',
                            label: '主键'
                        },
                            {
                                field: 'custGroupNo',
                                label: '客群编号',
                                rules: [{
                                    required: true,
                                    message: '必填项',
                                    trigger: 'blur'
                                }]
                            },
                            {
                                field: 'custGroupName',
                                label: '客群名称',
                                rules: [{
                                    required: true,
                                    message: '必填项',
                                    trigger: 'blur'
                                }]
                            },
                            {
                                field: 'custGroupStatus',
                                label: '客群状态',
                                type: 'select',
                                dataCode: 'CUST_GROUP_STATE',
                                rules: [{
                                    required: true,
                                    message: '必填项',
                                    trigger: 'blur'
                                }]
                            }
                        ]
                    }],
                    updateButtons: [{
                        label: '保存',
                        type: 'primary',
                        hidden: false,
                        op: 'submit',
                        click: function(model, valid) {
                            if (valid) {
                                // model.lastChgUsr = me.userId;
                                me.dataEditSaveFn(model);
                                me.dialogFormVisible = false;
                                me.$refs.custGroupTable.remoteData();
                            }
                        }
                    },
                        {
                            label: '取消',
                            hidden: false,
                            click: function(model) {
                                me.dialogFormVisible = false;
                            }
                        }
                    ],
                    addVisible: false,
                    loading: false,
                    messageApproveUrl: '/api/marketCustGroup/getApprove' ,
                    messageApproveParam: {
                        orgId:yufp.session.org.id
                    },
					custInfoDialogVisible: false,
					custInfoData: {},
					custInfoUrl: '/api/marketCustGroup/getCustInfo',
					custInfoParams: {},
                };
            },
            mounted: function() {
                // window.console.info("当前用户" + yufp.session);
            },
            methods: {
                //修改按钮
                custGroupEdit: function() {
                    if (this.$refs.custGroupTable.selections.length !== 1) {
                        this.$message({
                            message: "请选择一条数据",
                            type: 'warning'
                        });
                        return false;
                    }
                    var row = this.$refs.custGroupTable.selections[0];
                    this.viewType = 'UPDATE';
                    this.dialogFormVisible = true;
                    this.updateFields[0].fields[0].hidden = true;
                    this.updateFields[0].fields[1].readonly = true;
                    this.$nextTick(function() {
                        this.$refs.datafilterForm.resetFn();
                        yufp.extend(this.$refs.datafilterForm.formModel, row);
                    });
                },
                // 修改保存
                dataEditSaveFn: function(row) {
                    var _this = this;
                    _this.currentRow = row;

                    yufp.service.request({
                        url: backend.appCommonService + '/api/marketCustGroup/saveGroup',
                        method: 'post',
                        data: _this.currentRow,
                        callback: function(code, message, response) {
                            if (code == '0') {
                                _this.$message({
                                    message: '修改成功'
                                });

                                _this.$refs.custGroupTable.remoteData();
                            } else {
                                _this.$message({
                                    message: '修改失败'
                                });
                            }
                        }
                    });
                },

                // 批量删除系统参数
                custGroupDelete: function() {
					if (this.$refs.custGroupTable.selections.length !== 1) {
					    this.$message({
					        message: "请选择需要删除的客户群组",
					        type: 'warning'
					    });
					    return false;
					}
                    var selection = this.$refs.custGroupTable.selections[0];
					if (selection.createUser != yufp.session.userCode) {
						this.$message({
							message: '只能删除自建客群',
							type: 'warning'
						});
						return;
					}
					var id = selection.id;
					var custGroupNo = selection.custGroupNo;
					// var ids = '';
     //                var filterSelecttions = this.$refs.custGroupTable.selections;
     //                if (filterSelecttions.length > 0) {
     //                    for (var i = 0; i < filterSelecttions.length; i++) {
					// 		if (filterSelecttions[i].createUser != yufp.session.userCode) {
					// 			this.$message({
					// 				message: '只能删除自建客群',
					// 				type: 'warning'
					// 			});
					// 			return;
					// 		}
     //                        // 记录多选用于多删
     //                        if (filterSelecttions.length === 1) {
     //                            ids = filterSelecttions[i].id;
     //                        } else {
     //                            ids = ids + ',' + filterSelecttions[i].id;
     //                        }
     //                    }
     //                } else {
     //                    this.$message({
     //                        message: '请选择需要删除的客户群组'
     //                    });
     //                    return false;
     //                }
                    var _this = this;
                    _this.$confirm('确认删除客户群组?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(function() {
                        // yufp.service.request({
                        //     url: backend.appCommonService + '/api/marketCustGroup/batchDeleteGroup/' + ids,
                        //     method: 'post',
                        //     data: {
                        //         ids: ids
                        //     },
                        //     callback: function(code, message, response) {
                        //         if (code == '0') {
                        //             _this.$message({
                        //                 message: '删除成功'
                        //             });
                        //             _this.$refs.custGroupTable.remoteData();
                        //         } else {
                        //             // alert('删除失败！');
                        //             _this.$message({
                        //                 message: '删除失败'
                        //             });
                        //         }
                        //     }
                        // });
						yufp.service.request({
						    url: backend.appCommonService + '/api/marketCustGroup/deleteGroup',
						    method: 'post',
						    data: {
						        id: id,
								custGroupNo:custGroupNo
						    },
						    callback: function(code, message, response) {
						        if (code == '0') {
									if(response.data=='0'){
										_this.$message({
										    message: '当前客群已有营销任务，不可删除'
										});
									}else{
										_this.$message({
										    message: '删除成功'
										});
										_this.$refs.custGroupTable.remoteData();
									}
						            
						        } else {
						            // alert('删除失败！');
						            _this.$message({
						                message: '删除失败'
						            });
						        }
						    }
						});
                    });
                },
                custGroupSendMessage: function() {
                    if (this.$refs.custGroupTable.selections.length !== 1) {
                        this.$message({
                            message: "请选择一条数据",
                            type: 'warning'
                        });
                        return false;
                    }
                    this.addVisible = true;
                    if (this.$refs.templetForm != null) {
                        this.$refs.templetForm.resetFields();
                    }
                },
                addSubmit: function() {
                    var vm = this;
                    this.$refs.templetForm.validate(function(valid) {
                        if (valid) {
                            vm.loading = true;
                            window.console.info(vm.$refs.templetForm);
                            var groupsdata = vm.$refs.custGroupTable.selections[0];
                            // var groupsdata = []; // 客户信息
                            // for (var i = 0; i < groupSelecttions.length; i++) {
                            // 	var custsInfo = {};
                            // 	custsInfo['custNo'] = groupSelecttions[i].custIdBase;
                            // 	custsInfo['gridId'] = groupSelecttions[i].gridId;
                            // 	custsInfo['secondGridId'] = groupSelecttions[i].secondGridId;
                            // 	custsInfo['userNo'] = groupSelecttions[i].userNo;
                            // }
                            // groupsdata.push(custsInfo);
                            var modelType = vm.$refs.templetForm.formdata.modelType;
                            var modelInfo = vm.$refs.templetForm.formdata.modelInfo;
                            var approverNo = vm.$refs.templetForm.formdata.approverNo;
                            var addParam = {
                                userId: yufp.session.userCode,
                                userName: yufp.session.userName,
                                modelType: modelType,
                                modelInfo: modelInfo,
                                approverNo: approverNo,
                                // custGroupInfo: groupsdata
                                groupId: groupsdata.id,
                                custGroupNo: groupsdata.custGroupNo,
                                gridId: groupsdata.gridId
                            };
                            yufp.service.request({
                                method: 'POST',
                                // url: '/api/wpMessage/addTemplet',
                                url: '/api/marketCustGroup/insertApprove',
                                data: JSON.stringify(addParam),
                                callback: function(code, message, response) {
                                    if (code == 0) {
                                        vm.$message({
                                            message: '保存成功',
                                            type: 'success'
                                        });
                                        vm.addVisible = false;
                                        vm.$refs.custGroupTable.remoteData();

                                    }
                                    vm.loading = false;
                                }
                            });
                        }
                    });
                },
                addCancel: function() {
                    this.addVisible = false;
                    if (this.$refs.templetForm != null) {
                        this.$refs.templetForm.formdata = {};
                    }
                },
                getTemInfo: function(event){
                    if(event!=null){
                        var self = this;
                        var modelType = event;
                        yufp.service.request({
                            method: 'GET',
                            url: '/api/marketCustGroup/selectMessageTemInfo',
                            data: {modelType: modelType	},
                            callback: function(code, message, response) {
                                var data = response.data;
                                var modelInfo =data.modelInfo;
                                self.$refs.templetForm.formdata.modelInfo=data.modelInfo;
                            }
                        });
                    }
                },
				handleClick: function(row) {
					var _this = this;
					var custInfoParams = {
						condition: JSON.stringify({
							userId: yufp.session.userId,
							userName: yufp.session.userName,
                            orgId: yufp.session.org.id,
							roleCode: roleCode,
							custGroupNo: row.custGroupNo
							
						})
					};
					_this.custInfoParams = custInfoParams;
					_this.custInfoDialogVisible = true;
					_this.$nextTick(function() {
						_this.$refs.custInfoTable.resetFields();
					});
					
				
				}
            },
        });
    };

    // 消息处理
    exports.onmessage = function(type, message) {

    };

    // page销毁时触发destroy方法
    exports.destroy = function(id, cite) {

    };
});
